package com.zhanglijie.improve.atomic.four;

import java.util.concurrent.atomic.AtomicReference;

import com.sun.jna.platform.unix.X11;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/6 0006 23:29
 */
public class MyStack {
    private AtomicReference<Node> stackHead = new AtomicReference();
    static class Node{
        int value;
        Node next;
        public Node(int value){
            this.value = value;
        }
    }

    public void push(Node node){
        while (true) {//todo 我觉得这个好像不安全
            Node head = stackHead.get();
            node.next = head;
            if (stackHead.compareAndSet(head, node)) {
                return;
            }
        }
    }

    public Node pop(){
        while(true) {
            Node node = stackHead.get();
            if (node == null) {
                System.out.println("栈顶元素为空");
                return null;
            }
            Node next = node.next;
            if (stackHead.compareAndSet(node, next)) {
                node.next = null;
                return node;
            }
        }
    }

    public void printStack(){
        Node node = stackHead.get();
        while(node != null){
            System.out.println("最终打印栈元素"+node.value);
            node = node.next;
        }
    }
}
